<?php
namespace app\tuchuang\controller;

use app\common\controller\Api;

class Apis extends Api
{
    //分享域名
    private $imageCdn   = '';
    //远程图片
    private $imageUrl   = '';
    //允许类型
    private $imageType  = [];
    //图片内型contentType
    private $mimeType   = '';
    //图片内容
    private $imgContent = '';
    //临时文件名
    private $fileName   = 'images';
    //权限相关
    protected $auth = [
         'check'       => true,
         'none_login'  => ['tuchuang/index/index'],
         'none_right'  => [],
         'error_login' => 'user/login/index',
         'error_right' => 'user/group/index',
    ];
    
    public function _initialize()
    {
        $this->imageUrl  = DcEmpty(config('tuchuang.link_default'), 'https://cdn.daicuo.cc/images/gzh/dc_01.jpg');
        
        $this->imageType = config('tuchuang.mime_type');
        
        if(!config('common.upload_cdn')){
            $this->imageCdn = $this->request->root(true).'/';
        }else{
            $this->imageCdn = trim(config('common.upload_cdn'));
        }
        
		parent::_initialize();
    }
    
    //上传图片
    public function upload()
    {
        $result = [];
        $files = \daicuo\Upload::save_all($this->request->file('file'));
        if($files['data']){
            $result['slug'] = $files['data']['slug'];
            $result['url']  = $this->imageCdn.trim(config('common.upload_path'),'/').'/'.$files['data']['attachment'];
        }
        if($result){
            return json(['code'=>1,'msg'=>'ok','data'=>$result]);
        }else{
            return json(['code'=>0,'msg'=>lang('tuchang/error/upload'),'data'=>'']);
        }
    }
    
    //外链图片转换
    public function change()
    {
        $result = ['slug'=>'','url'=>''];
        //图片外链地址
        $url    = input('request.url/s');
        if(!$url){
            return json(['code'=>0,'msg'=>lang('tuchang/error/urlEmpty'),'data'=>$result]);
        }
        //外链协议
        if( !in_array(parse_url($url,PHP_URL_SCHEME),['https','http','ftp']) ){
            return json(['code'=>0,'msg'=>lang('tuchang/error/urlWrong'),'data'=>$result]);
        }
        //验证加速域名
        if( config('tuchuang.link_referer') ){
            $referers = explode(',', config('tuchuang.link_referer'));
            if( !in_array($args['host'], $referers) ){
                return json(['code'=>0,'msg'=>lang('tuchang/error/referer'),'data'=>$result]);
            }
        }
        //实例化文件操作类
        $file = new \files\File();
        //md5文件名
        $this->fileName = md5($url);
        //保存文件名
        $saveName = trim(config('common.upload_path'), '/').'/'.substr($this->fileName,0,4).'/'.$this->fileName;
        //判断文件是否存在
        if($file->f_has($saveName)){
            return json(['code'=>1,'msg'=>'ok','data'=>['slug'=>$this->fileName,'url'=>$this->imageCdn.$saveName]]);
        }
        //CURL请求远程图片
        $this->curl($url);
        //文件类型验证
        if( !in_array($this->mimeType, $this->imageType) ){
            return json(['code'=>0,'msg'=>lang('tuchang/error/mimeWrong'),'data'=>$result]);
        }
        //文件内容验证
        if(!$this->imgContent){
            return json(['code'=>0,'msg'=>lang('tuchang/error/contentEmpty'),'data'=>$result]);
        }
        //下载远程图片到本地
        if(!$file->write($saveName, $this->imgContent)){
            return json(['code'=>0,'msg'=>lang('tuchang/error/saveEmpty'),'data'=>$result]);
        }
        //附件信息保存数据库
        imgInfoInsert($this->site['user']['user_id'], $this->fileName, $this->mimeType, strlen($this->imgContent), $url);
        //返回地址
        return json(['code'=>1,'msg'=>'ok','data'=>['slug'=>$this->fileName,'url'=>$this->imageCdn.$saveName]]);
    }
    
    //图片地址加密接口（生成加密后的地址）
    public function encode()
    {
        $imgUrl = input('request.url/s');
        if(!$imgUrl){
            return json(['code'=>0,'msg'=>lang('tuchang/error/urlEmpty'),'data'=>'']);
        }
        //返回结果
        return json(['code'=>1,'msg'=>'ok','data'=>$this->urlEncode($imgUrl)]);
    }
    
    //图片地址解密接口（还原加密地址）
    public function decode()
    {
        $imgUrl = input('request.url/s');
        if(!$imgUrl){
            return json(['code'=>0,'msg'=>lang('tuchang/error/urlEmpty'),'data'=>'']);
        }
        
        //验证解密
        $imgUrl = $this->urlDecode(input('request.url/s'));
        if(!$imgUrl){
            return json(['code'=>0,'msg'=>'error','data'=>$imgUrl]);
        }
        
        //返回结果
        return json(['code'=>1,'msg'=>'ok','data'=>$imgUrl]);
    }
    
    //图片地址解析接口(生成解析外链)
    public function parse()
    {
        $imgUrl = input('request.url/s');
        if(!$imgUrl){
            return json(['code'=>0,'msg'=>lang('tuchang/error/urlEmpty'),'data'=>'']);
        }
        
        config('common.app_domain', true);
        
        $imgUrl = $this->urlEncode($imgUrl);
        
        return json(['code'=>1,'msg'=>'ok','data'=>DcUrl('tuchuang/index/read',['url'=>$imgUrl])]);
    }
    
    //图片地址加密处理
    private function urlEncode($imgUrl){
        if(!$imgUrl){
            return $this->imageUrl;
        }
        if( config('tuchuang.link_encode') ){
            foreach( explode(',', config('tuchuang.link_encode')) as $key=>$function){
                $imgUrl = $function($imgUrl);
            }
        }
        return $imgUrl;
    }
    
    //图片地址解密处理
    private function urlDecode($imgUrl){
        if(!$imgUrl){
            return $this->imageUrl;
        }
        if( config('tuchuang.link_decode') ){
            foreach( explode(',', config('tuchuang.link_decode')) as $key=>$function){
                $imgUrl = $function($imgUrl);
            }
        }
        return DcEmpty($imgUrl, $this->imageUrl);
    }
    
    //CURL获取文件内容
    private function curl($url='')
    {
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt ($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt ($ch, CURLOPT_ENCODING, "");
        //https自动处理
        $http = parse_url($url);
        if($http['scheme'] == 'https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        //设置图片内容
        $this->imgContent = curl_exec($ch);
        //设置图片类型（CONTENT_TYPE）
        $contentType      = explode(";", curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
        $this->mimeType   = $contentType[0];
        //关闭链接
        curl_close($ch);
    }
}